import React, { useState, useEffect } from 'react';
import { Modal, Form, message, DatePicker, InputNumber } from 'antd';
import { finishTask, getTurnFinishInfo } from '@/pages/Task/services';
import moment from 'moment';
import { useAfterTaskList } from '@/pages/Task/hooks';
import { TimeFormat } from '@/pages/Task/utils';
import { ModalTable, LimitedTextArea } from '@/pages/Task/components';

import { MODAL_DEFAULT_PARAM, MODAL_FORCE_PARAM, FORM_DEFAULT_LAYOUT } from '../config';
import FileFormItem from './components/FileFormItem';
import styles from './index.less';

const minuteToHours = value => (value ? Math.floor(value / 6) / 10 : 0);
const timeOrDate = d => (d.indexOf('23:59:59') === -1 ? 'time' : 'date');
const getFormat = (type, toServer) => {
    if (type === 'date') {
        return toServer ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD';
    }
    return toServer ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD HH:mm';
};
const getData = async taskId => {
    const res = await getTurnFinishInfo(taskId);
    const { code, data, msg } = res;
    if (code !== 10000 || !data) {
        return message.error(msg || '操作失败~~~');
    }
    return data;
};
const TurnFinishActionModal = ({ form, taskId, visible, setVisible, onOk }) => {
    // console.log('TurnFinishActionModal -> taskId', taskId);
    const [taskRecord, setTaskRecord] = useState({});
    const { getFieldDecorator, validateFields, getFieldValue } = form;
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [initTimeType, setInitTimeType] = useState('date');
    const [realEndTimeMode, setRealEndTimeMode] = React.useState(initTimeType);
    useEffect(() => {
        if (!visible) {
            return;
        }
        getData(taskId).then(res => {
            const initType = timeOrDate(res.planEndTime);
            setInitTimeType(initType);
            setRealEndTimeMode(initType);
            setTaskRecord(res);
        });
    }, [taskId]);
    const {
        acceptanceEmployeeName, // 验收人姓名
        planEndTime, // 截止时间
        hasSubTask, // 是否有子任务
        subTaskLatestEndTime, // 子任务最晚提交时间
        subTaskWorkDurationTotal, // 子任务总耗时
        estimateWorkDuration, // 预估工时（分钟）
        actualStartTime // 实际开始时间
    } = taskRecord;
    const [tableParamsState, setTableParamsState] = useState({ actualTime: moment().format(getFormat('date', true)) });
    // #region 显示逻辑
    const defaultStr = '0天0小时0分钟';
    // 截止时间 - 显示
    const getPlanEndTimeDisplay = () => planEndTime && moment(planEndTime).format(getFormat(initTimeType));
    // 逾期时间 - 显示
    const getOverdueDateDisplay = () => {
        const actualEndTime = getFieldValue('actualEndTime');
        if (!actualEndTime || !planEndTime) {
            return defaultStr;
        }
        const actualEndTimeToServer = moment(actualEndTime.format(getFormat(realEndTimeMode, true)));
        const planEndTimeToServer = moment(planEndTime);
        if (actualEndTimeToServer.isBefore(planEndTimeToServer)) {
            return defaultStr;
        }
        const diff = actualEndTimeToServer.diff(planEndTimeToServer, 'minutes');
        return TimeFormat(diff, 24);
    };
    // 预估工时 - 显示
    const estimateWorkDurationDisplay = estimateWorkDuration && TimeFormat(estimateWorkDuration);
    // 实际工时 转换 天 时 分- 显示
    const getRealTimeHourSuffix = () => {
        const actualWorkDuration = getFieldValue('actualWorkDuration');
        if (!actualWorkDuration) {
            return defaultStr;
        }
        return TimeFormat(actualWorkDuration * 60);
    };
    // 逾期工时 - 显示
    const getOverdueWorkDisplay = () => {
        let actualWorkDuration = getFieldValue('actualWorkDuration');
        if (!actualWorkDuration || !estimateWorkDuration) {
            return defaultStr;
        }
        actualWorkDuration *= 60;
        if (actualWorkDuration < estimateWorkDuration) {
            return defaultStr;
        }
        return TimeFormat(actualWorkDuration - estimateWorkDuration);
    };
    // 子任务最晚提交时间 - 只显示日期部分
    const subTaskLatestEndTimeDisplay = hasSubTask ? moment(subTaskLatestEndTime).format(getFormat('date')) : '';
    // 子任务总工时
    const subTaskWorkDurationTotalHours = hasSubTask ? minuteToHours(subTaskWorkDurationTotal) : '';
    // #endregion
    // 时间变化时
    const handleTimeChange = val => {
        setTableParamsState({ actualTime: val ? val.format(getFormat(realEndTimeMode, true)) : '' });
    };
    const handleOk = () => {
        validateFields((err, values) => {
            console.log('TurnFinishActionModal -> values', values);
            if (err) {
                return;
            }
            const { actualEndTime, actualWorkDuration, remark, resourceRelation } = values;
            const files = (resourceRelation && [resourceRelation.uploadResourceFile]) || [];
            const actualEndTimeToServer = actualEndTime.format(getFormat(realEndTimeMode, true));
            setConfirmLoading(true);
            finishTask(taskId, actualEndTimeToServer, actualWorkDuration * 60, remark || '', files)
                .then(res => {
                    const { code, msg } = res;
                    if (code !== 10000) {
                        message.error(msg || '操作失败~~~');
                        return;
                    }
                    if (onOk) {
                        onOk();
                    }
                    setVisible(false);
                })
                .finally(() => {
                    setConfirmLoading(false);
                });
        });
    };

    const handleRealEndTimePanel = (value, mode) => {
        setRealEndTimeMode(mode);
    };

    return (
        <Modal
            {...MODAL_DEFAULT_PARAM}
            title="转已完成"
            visible={visible}
            width={840}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            wrapClassName={styles.miniMarginBottom}
            onCancel={() => setVisible(false)}
            {...MODAL_FORCE_PARAM}
        >
            <Form {...FORM_DEFAULT_LAYOUT}>
                {/* 有验收人才显示 */}
                {acceptanceEmployeeName && (
                    <Form.Item label="温馨提示">
                        确定后，需由验收人【{acceptanceEmployeeName}】通过后方可生效；
                    </Form.Item>
                )}
                <Form.Item label="截止时间" className={styles.disabledItem}>
                    {getPlanEndTimeDisplay()}
                </Form.Item>
                <Form.Item label="实际完成时间">
                    <div>
                        {getFieldDecorator('actualEndTime', {
                            initialValue: moment(),
                            rules: [
                                {
                                    required: true,
                                    message: '请选择实际完成时间！'
                                },
                                {
                                    validator(rule, value, callback) {
                                        // 与子任务最晚完成时间只比较日期部分
                                        if (
                                            hasSubTask &&
                                            moment(value.format(getFormat('date'))).isBefore(
                                                moment(subTaskLatestEndTimeDisplay)
                                            )
                                        ) {
                                            callback('不可早于子任务最晚完成的时间');
                                        } else if (
                                            moment(value.format(getFormat(realEndTimeMode, true))).isBefore(
                                                moment(actualStartTime)
                                            )
                                        ) {
                                            callback('不可早于实际开始时间');
                                        } else {
                                            callback();
                                        }
                                    }
                                }
                            ]
                        })(
                            <DatePicker
                                showTime
                                placeholder="请选择实际完成时间"
                                format={getFormat(realEndTimeMode)}
                                onPanelChange={handleRealEndTimePanel}
                                onChange={handleTimeChange}
                            />
                        )}
                    </div>
                    <div>
                        {hasSubTask && (
                            <div>
                                输入时间不可早于子任务最晚完成的时间
                                <span style={{ color: '#ffa808' }}>{subTaskLatestEndTimeDisplay}</span>
                            </div>
                        )}
                    </div>
                </Form.Item>
                <Form.Item label="逾期时间">{getOverdueDateDisplay()}</Form.Item>
                <Form.Item label="预估工时" className={styles.disabledItem}>
                    {estimateWorkDurationDisplay}
                </Form.Item>
                <Form.Item label="实际工时">
                    <div>
                        {getFieldDecorator('actualWorkDuration', {
                            rules: [
                                {
                                    required: true,
                                    message: '请输入实际工时！'
                                },
                                {
                                    validator(rule, value, callback) {
                                        if (hasSubTask && value < subTaskWorkDurationTotalHours) {
                                            callback('不可小于子任务已耗工时总和！');
                                        } else {
                                            callback();
                                        }
                                    }
                                }
                            ]
                        })(
                            <InputNumber
                                min={0}
                                max={9999.9}
                                precision={1}
                                formatter={value => `${value}`.replace('.0', '')}
                                placeholder="请输入"
                                style={{ width: 80 }}
                            />
                        )}
                        &nbsp;&nbsp;小时&nbsp;&nbsp;&nbsp;&nbsp;{getRealTimeHourSuffix()}
                    </div>
                    {hasSubTask && (
                        <div>
                            该任务下所有子任务已耗总工时为
                            <span style={{ color: '#ffa808' }}>{subTaskWorkDurationTotalHours}</span>
                            小时，当前输入项不可小于总工时
                        </div>
                    )}
                </Form.Item>
                <Form.Item label="逾期工时" className={styles.disabledItem}>
                    {getOverdueWorkDisplay()}
                </Form.Item>
                <Form.Item label="备注说明">
                    {getFieldDecorator('remark')(
                        <LimitedTextArea placeholder="请输入备注说明" maxLength={500} rows={6} />
                    )}
                </Form.Item>
                <FileFormItem fieldName="resourceRelation" form={form}></FileFormItem>
            </Form>
            <ModalTable
                title="逾期影响提示：当前任务已逾期，或将影响以下后置任务进度"
                taskId={taskId}
                shouldHide
                type="finish"
                params={tableParamsState}
                loadData={useAfterTaskList}
            />
        </Modal>
    );
};

export default Form.create()(TurnFinishActionModal);
